package com.itheima.test;

public class Demo_002 {
    public static void main(String[] args) {
        //使用二分查找,查找元素对应的索引值;
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int number = 4;
        int index = getIndex(arr, number);
        System.out.println(index);
    }

    private static int getIndex(int[] arr, int number) {
        int min = 0;
        int max = arr.length - 1;
        while (min <= max) {
            int mid = min + (max - min) / 2;
            if (arr[mid] > number) {
                max = mid - 1;
            } else if (arr[mid] < number) {
                min = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
